﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Payroll.Repositories;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Exceptions;
using PmSoft.Repositories;

namespace Modules.Payroll
{
    [UseDI(ServiceLifetime.Scoped)]
    public class WagePayrollDetailService
    {
        private readonly WagePayrollDetailRepository repository;
        private readonly WagePayrollRepository payrollRepository;
        private readonly IApplicationContext applicationContext;
        private readonly ILogger logger;

        public WagePayrollDetailService(WagePayrollDetailRepository repository, WagePayrollRepository payrollRepository, IApplicationContext applicationContext, ILogger<WagePayrollDetailService> logger)
        {
            this.repository = repository;
            this.payrollRepository = payrollRepository;
            this.applicationContext = applicationContext;
            this.logger = logger;
        }

        public IEnumerable<WagePayrollDetail> GetPayrollDetailsByPayrollId(int payrollId)
        {
            return repository.GetPayrollDetailsByPayrollId(payrollId);
        }

        public IPagedList<WagePayrollDetail> GetPayrollDetails(WagePayrollQuery query, int pageIndex, int pageSize)
        {
            return repository.GetPayrollDetails(query, pageIndex, pageSize);
        }

        public void Create(int payrollId, IEnumerable<WagePayrollDetail> wagePayrollDetails)
        {
            WagePayroll? wagePayroll = payrollRepository.Get(payrollId);
            if (wagePayroll == null)
                throw new BusinessException($"工资单信息不存在");
            try
            {
                applicationContext.Transaction.Begin();//开始事务

                repository.CreateOrUpdate(payrollId, wagePayrollDetails);

                wagePayroll.NumberPeople = wagePayrollDetails.Count();
                wagePayroll.AmountApplied = wagePayrollDetails.Sum(x => x.AmountApplied);

                payrollRepository.Update(wagePayroll);
                applicationContext.Transaction.Complete();//完成事务
            }
            catch (Exception ex)
            {
                applicationContext.Transaction.Abort();//回滚事务
                logger.LogError(ex, "工资单明细数据事务执行失败");
                throw new BusinessException("工资单明细数据事务执行失败");
            }
        }

        public void Update(WagePayrollDetail entity)
        {
            repository.Update(entity);
        }

        public IEnumerable<WagePayrollDetail> GetPayrollDetailsByPersonIdAndMonth(int personId, int month)
        {
            return repository.GetPayrollDetailsByPersonId(personId).Where(a => a.Month == month);
        }
    }
}